<?php  namespace App\Api\Models;

use Input;
use App\Api\Models\Goods;
use App\Api\Models\CabinetCell;
use App\Api\Models\Cabinet;
use Log;
class User extends BaseModel{
    
	//表明
	protected $table = 'user';
	//主键
	protected $primaryKey = 'id';
    //验证码
    private $code;


    //获取验证码
    public function getVerifyCode() {
        $mobile = Input::get('mobile');
        $retArr = [];
        if(!$mobile){
            $retArr = array(
                "msg" => "请传入手机号",
                "result" => 0,
            );
            return $retArr;
        }
        $result=$this->SendSMS($mobile);
        if($result==1)
        {
            //未做验证n分钟内是否有发送
            $phoneMsg = new PhoneMsg();
            $phoneMsg->phone = $mobile;
            $phoneMsg->code = $this->code;
            $phoneMsg->content = $this->code;
            $phoneMsg->status = 1;
            $phoneMsg->save();
            $retArr = array(
                "msg"=>"发送成功",
                "code"=>$this->code,
                "result"=>1,
            );
        }
        if($result==2){
            $retArr = array(
                "msg"=>"发送失败",
                "result"=>2,
            );
        }
        if($result==3)
        {
            $retArr = array(
                "msg"=>"报错,联系管理员",
                "result"=>3,
            );
        }
        return $retArr;
    }
    //发送验证码
    public function SendSMS($mobile){
        $url='http://http.duanxin.cm/OpenPlatform/OpenApi';           //接口地址
        $ac='1001@901012130001';		                             //用户账号
        $authkey = '4B0D74375E2F4690B5432D0EB519DFDF';		         //认证密钥
        $cgid='1';  
        $this->code=$this->random(4,0);                                            //通道组编号
        $c = '您好,您的验证码是'.$this->code.'，请在15分钟内完成验证。【摩力晒耳】';		 //内容
        $m= $mobile;	                                         //号码
        $csid='';                                                   //签名编号 ,可以为空时，使用系统默认的编号
        $t='';                                                       //发送时间,可以为空表示立即发送,yyyyMMddHHmmss 如:20130721182038
        $data = array
        (
            'action'=>'sendOnce',                                //发送类型 ，可以有sendOnce短信发送，sendBatch一对一发送，sendParam	动态参数短信接口
            'ac'=>$ac,					                         //用户账号
            'authkey'=>$authkey,	                             //认证密钥
            'cgid'=>$cgid,                                       //通道组编号
            'm'=>$m,		                                     //号码,多个号码用逗号隔开
            //'c'=>iconv('gbk','utf-8',$c),		                 //如果页面是gbk编码，则转成utf-8编码，如果是页面是utf-8编码，则不需要转码
            'c'=>$c,
            'csid'=>$csid,                                       //签名编号 ，可以为空，为空时使用系统默认的签名编号
            't'=>$t                                              //定时发送，为空时表示立即发送
        );
        $re= $this->postSMS($url,$data);			                     //POST方式提交
        preg_match_all('/result="(.*?)"/',$re,$res);
        if(trim($res[1][0]) == '1' )  //发送成功 ，返回企业编号，员工编号，发送编号，短信条数，单价，余额
        {

            preg_match_all('/\<Item\s+(.*?)\s+\/\>/',$re,$item);
            for($i=0;$i<count($item[1]);$i++){
            preg_match_all('/cid="(.*?)"/',$item[1][$i],$cid);
            preg_match_all('/sid="(.*?)"/',$item[1][$i],$sid);
            preg_match_all('/msgid="(.*?)"/',$item[1][$i],$msgid);
            preg_match_all('/total="(.*?)"/',$item[1][$i],$total);
            preg_match_all('/price="(.*?)"/',$item[1][$i],$price);
            preg_match_all('/remain="(.*?)"/',$item[1][$i],$remain);

            $send['cid']=$cid[1][0];             //企业编号
            $send['sid']=$sid[1][0];             //员工编号
            $send['msgid']=$msgid[1][0];         //发送编号
            $send['total']=$total[1][0];         //计费条数
            $send['price']=$price[1][0];         //短信单价
            $send['remain']=$remain[1][0];       //余额
            $send_arr[]=$send;                   //数组send_arr 存储了发送返回后的相关信息
            }
            //echo "发送成功,状态为".$res[1][0];   //发送成功返回的值
            return 1;
        }
        else{  //发送失败的返回值
            switch(trim($res[1][0])){
                case  0: echo "帐户格式不正确(正确的格式为:员工编号@企业编号)";break; 
                case  -1: echo "服务器拒绝(速度过快、限时或绑定IP不对等)如遇速度过快可延时再发";break;
                case  -2: echo " 密钥不正确";break;
                case  -3: echo "密钥已锁定";break;
                case  -4: echo "参数不正确(内容和号码不能为空，手机号码数过多，发送时间错误等)";break;
                case  -5: echo "无此帐户";break;
                case  -6: echo "帐户已锁定或已过期";break;
                case  -7:echo "帐户未开启接口发送";break;
                case  -8: echo "不可使用该通道组";break;
                case  -9: echo "帐户余额不足";break;
                case  -10: echo "内部错误";break;
                case  -11: echo "扣费失败";break;
                default:break;
           }
           return 0;
        }
    }
    public function postSMS($url,$data=''){
        $row = parse_url($url);
        $host = $row['host'];
        $port = 80;
        $file = $row['path'];
        $post="";
        while (list($k,$v) = each($data)) 
        {
            $post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
        }
        $post = substr( $post , 0 , -1 );
        $len = strlen($post);
        $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
        if (!$fp) {
            return "$errstr ($errno)\n";
        } else {
            $receive = '';
            $out = "POST $file HTTP/1.0\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Content-type: application/x-www-form-urlencoded\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Content-Length: $len\r\n\r\n";
            $out .= $post;		
            fwrite($fp, $out);
            while (!feof($fp)) {
                    $receive .= fgets($fp, 128);
            }
            fclose($fp);
            $receive = explode("\r\n\r\n",$receive);
            unset($receive[0]);
            return implode("",$receive);
        }
    }
    /**
     * 获取随机数
     * @param int $length
     * @param int $numeric
     * @return string
     */
    function random($length = 4 , $numeric = 0){
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = '0123456789';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
     //验证验证码
    public function isVerifyCode($mobile, $code) {
        $phoneMsg = PhoneMsg::select('*')
                ->where('phone','=',$mobile)
                ->where('code','=',$code)
                ->where('status','=',1)
                ->first();
        if($phoneMsg){
            if($code == $phoneMsg->code){
                return true;
            }
        }
        return false;
    }
    //用户登录-注册
    public function register() {
        $mobile = Input::get('mobile');
        $code = Input::get('code');
        $retArr = [];
        if(!$mobile){
            $retArr = array(
                "msg" => "请传入手机号",
                "result" => 0,
            );
            return $retArr;
        }
        if(!$code){
            $retArr = array(
                "msg" => "请输入验证码",
                "result" => 0,
            );
            return $retArr;
        }
        $ret = $this->isVerifyCode($mobile, $code);
        if(!$ret){
            $retArr = array(
                "msg" => "验证码已过期，请重新申请验证码~！",
                "result" => 0,
            );
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->first();
        if($user && ($user->status == 2 || $user->is_delete == 1)){
            $retArr = array(
                "msg" => "用户被禁用",
                "result" => 0,
            );
            return $retArr;
        }
        if($user && $user->status == 0){
            $user->status = 1; //正常
            $user->save();
        }else {
            $user = new User();
            $user->phone = $mobile;
            $user->nickname = "新手";
            $user->status = 1;
            $user->phone = $mobile;
            $user->reg_time = time();
            $ret = $user->save();
            if(!$ret){
                $retArr = array(
                    "msg" => "注册失败，请及时联系管理员~！",
                    "result" => 0,
                );
                return $retArr;
            }
        }
        $temp['UserNM'] = "新手";
        $temp['mobile'] = $mobile;
        $temp['regtime'] = $user->time;
        $temp['customerID'] = 1;
        $temp['currentCode'] = $code;
        $temp['isstatus'] = 1;
        $temp['Vip'] = 0;
        $temp['Count'] = 0;
        $temp['email'] = "";
        $temp['addr'] = "";
        $data[] = $temp;
        $retArr = array(
            "msg" => "注册成功",
            "result" => 1,
            "data"=>$data,
        );
        return $retArr;
    }
    
//    //用户登录
//    public function login() {
//        $mobile = Input::get('mobile');
//        $code = Input::get('code');
//        $retArr = [];
//        if(!$mobile){
//            $retArr["msg"]= "请传入手机号";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
//        if(!$code){
//            $retArr["msg"]= "请输入验证码";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
//        $user = $this->select('*')
//                ->where('phone','=',$mobile)
//                ->where('status','=',1)
//                ->where('is_delete','=',0)
//                ->first();
//        if(!$user){
//            $retArr["msg"]= "无此用户";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
//        $ret = $this->isVerifyCode($mobile, $code);
//        if(!$ret){
//            $retArr["msg"]= "验证码已过期，请重新申请验证码~！";
//            $retArr["result"] = 0;
//            return $retArr;
//        }
//        $retArr["msg"]= "获取成功";
//        $retArr["result"] = 0;
//        $userArr = $this->getUserObj($user);
//        return array_merge($retArr,$userArr);
//    }
    public function getUserXingZhi() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
            $retArr["msg"]= "无此用户";
            $retArr["result"] = 0;
            return $retArr;
        }
//        $retArr["msg"]= "获取成功";
        $retArr["result"] = 1;
        $cls="个人";
        if($user->client_id && $user->is_bind == 2){
            $cls="企业";
        }
        $retArr["cls"] = $cls;
        $retArr["msg"] = "";
        $retArr["service"] = "无";
        $user->score_jf = 0;
        //添加微信
        if($user->wx_open_id){
            $wxUser = WxUser::select('*')
                ->where('open_id','=',$user->wx_open_id)
                ->first();
            if(!$wxUser){
                $wxUser = new WxUser();
                $wxUser->open_id = $user->wx_open_id;
                $wxUser->save();
            }
            $user->score_jf = $wxUser->score_jf;
        }
        $userArr = $this->getUserObj($user);
        
//        echo "{ \"msg\": \"获取成功\",\"result\": 1,\"mobile\":\"".$mobile."\",\"cls\":\"".$cls."\",
//        \"msg\":\"".$msg."\",\"UserNM\":\"".$user["UserNM"]."\",\"mobile\":\"".$mobile."\",
//        \"regtime\":".$user["regTime"].",\"customerID\":\"".$user["customerID"]."\",
//        \"CustomerNM\":\"".$Customer["CustomerNM"]."\",\"currentCode\":\"".$user["currentCode"]."\",
//        \"isstatus\":".$user["isStatus"].",\"Money\":".$this->M_User->getEndMoney($mobile).",
//        \"Count\":".$this->M_User->getCount($mobile).",\"email\":\"".$user["Email"]."\",
//        \"addr\":\"".$user["Addr"]."\",\"service\":\"".$service."\"}";
        return array_merge($retArr,$userArr);
    }
    public function getUserInfo() {
        $mobile = Input::get('mobile');
        $open_id = Input::get('open_id');//
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
            $user = new User();
            $user->status = 1;
            $user->reg_time = time();
            $user->phone = $mobile;
        } 
        if($open_id){
            $user->wx_open_id = $open_id;
        }
        $user->save();
        $user->score_jf = 0;
        //添加微信
        if($user->wx_open_id){
            $wxUser = WxUser::select('*')
                ->where('open_id','=',$user->wx_open_id)
                ->first();
            if(!$wxUser){
                $wxUser = new WxUser();
                $wxUser->open_id = $user->wx_open_id;
                $wxUser->save();
            }
            $user->score_jf = $wxUser->score_jf;
        }
        $retArr["msg"]= "获取成功";
        $retArr["result"] = 1;
       
        $userArr = $this->getUserObj($user);
        return array_merge($retArr,$userArr);
    }
    public function getUserObj($obj=null) {
        $temp['UserNM'] = $obj->nickname?$obj->nickname:"";
        $temp['mobile'] = $obj->phone;
        $temp['regtime'] = $obj->reg_time?$obj->reg_time:0;
        $temp['customerID'] = $obj->client_id;
        $temp['CustomerNM'] = "";
//        Log::info("用户信息=". json_encode($obj));
        if($obj->client_id && $obj->is_bind == 2){
            $client = Client::select('*')
                    ->where('id','=',$obj->client_id)
                    ->where('status','=',1)
                    ->where('is_delete','=',0)
                    ->first();
            if($client){
                $temp['CustomerNM'] = $client->name;
            }
        }
        $money = (float)$obj->balance + (float)$obj->song_money;
        $temp['Money'] = $money;
        $temp['currentCode'] = 0; //没啥用
        $temp['isstatus'] = $obj->status;
        $temp['Count'] = $obj->score_jf?$obj->score_jf:0; //$obj->score?$obj->score:0 
        $temp['email'] = $obj->email?$obj->email:"";
        $temp['addr'] = $obj->address?$obj->address:"";
        if($obj->gender == 2){
            $gender = "女";
        }else{
            $gender = "男";
        }
        $temp['sex'] = $gender;
        $temp['age'] = $obj->age?$obj->age:0;
        
        return $temp;
    }
    //更新用户
    public function upUserInfo(){
        $mobile = Input::get('mobile');
        $userNM = Input::get('userNM');
        $email = Input::get('email');
        $addr = Input::get('addr');
        $sex = Input::get('sex');
        $age = Input::get('age');
        $retArr["msg"]= "";
        $retArr["result"] = 0;
        if(!$mobile)
		{
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
			return $retArr;
		}
        if(!$userNM)
		{
            $retArr["msg"]= "请输入用户名";
            $retArr["result"] = 0;
			return $retArr;
		}
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
            $retArr["msg"]= "更新失败";
            $retArr["result"] = 0;
			return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
            $retArr["msg"]= "更新失败";
            $retArr["result"] = 0;
			return $retArr;
        }
        $user->phone = $mobile;
        $user->nickname = $userNM;
        if($addr){
            $user->address = $addr;
        }
        if($sex){
            $sex = trim($sex);
            switch ($sex){
                case '男': $user->gender = 1 ;break;
                case '女': $user->gender = 2 ;break;
                default :break;
            }
        }
        if($email){
            $user->email = email;
        }
        if($age){
            $user->age = $age;
        }
        $ret = $user->save();
        if(!$ret){
            $retArr["msg"]= "更新失败";
            $retArr["result"] = 0;
			return $retArr;
        }
        $retArr["msg"]= "更新成功";
        $retArr["result"] = 1;
        return $retArr;
    }
    //获取用户余额
    public function getUserMoney() {
        $mobile = Input::get('mobile');
        if(!$mobile)
        {
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = User::select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if(!$user){
            $retArr["msg"]= "请传入正确的手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $money = (float)$user->balance + (float)$user->song_money;
        $retArr["money"] = $money;
        $retArr["msg"]= "获取成功";
        $retArr["mobile"]= $mobile;
        $retArr["result"] = 1;
        return $retArr;
    }
    
    //用户充值记录
    public function getUserAddMoneyList() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $orderList = Orders::select('orders.*')
                ->join('user','user.id','=','orders.user_id')
                ->where('user.phone','=',$mobile)
                ->where('orders.is_delete','=',0)
                ->where('user.status','=',1)
                ->get();
        $retArr["msg"]= "获取成功";
        $retArr["result"] = 1;
        $data['data'] = [];
        if(count($orderList)>0){
            foreach ($orderList as $val){
                $temp = [];
                $temp['No'] = $val->id;
                $temp['money'] = $val->amount;
                $temp['addtime'] = date("Y-m-d H:i",$val->created_at->timestamp);
                switch ($val->type){
//                    11消费 2交押金 3退押金 4充值 5提现
                    case 1:
                        $type = "消费";
                        break;
                    case 2:
                        $type = "交押金";
                        break;
                    case 3:
                        $type = "退押金";
                        break;
                    case 4:
                        $type = "充值";
                        break;
                    case 5:
                        $type = "提现";
                        break;
                    default :
                        $type = "";
                        break;
                }
                $temp['cls'] = $type;
                $data['data'][] = $temp;
            }
        }else{
            //没有订单
        }
        return array_merge($retArr,$data);
    }
    
    //用户充值
    public function UserAddMoney() {
        $mobile = Input::get('mobile');
        $money = Input::get('money');
        $wxorder = Input::get('wxorder');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$money){
            $retArr["msg"]= "没有充值额度";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$wxorder){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        
        $songMoney = 0;
        if($money>=200 && $money<300){
            $songMoney=20;
        }
        if($money>=300 && $money<500){
            $songMoney=30;
        }
        if($money>=500){
            $songMoney=50;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            $order = new Orders();
            $order->user_id = $user->id;
            $order->amount = $money;
            $order->type = 4;
            $order->pay_type = 1;
            $order->wxorder = $wxorder;
            $order->status = 1;
            $order->save();
            //
            $user->song_money = $songMoney;
            $user->balance = $user->balance + $money;
            $ret = $user->save();
            if($ret){
                $retArr["msg"]= "充值成功";
                $retArr["mobile"]= $mobile;
                $retArr["money"]= $money;
                $retArr["result"] = 1;
                return $retArr;
            }
        }
        $retArr["msg"]= "报错，请联系管理员";
        $retArr["result"] = 0;
        return $retArr;
    }
    //获取消费记录
    public function getUserRendlst() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $goodsList = Orders::select('orders.*','goods.name as goodName','goods.icon as goodIcon')
                ->join('user','user.id','=','orders.user_id')
                ->join('goods','orders.goods_id','=','goods.id')
                ->where('orders.type','=',1)
                ->where('user.phone','=',$mobile)
//                ->where('user.status','!=',1)
                ->where('user.is_delete','=',0)
                ->where('orders.is_delete','=',0)
                ->orderBy('orders.start_time',"desc")
                ->get();
        $retArr["msg"]= "获取成功";
        $retArr["result"] = 1;
        $retArr["mobile"] = $mobile;
        $data['data'] = [];
        if(count($goodsList)){
            foreach ($goodsList as $key=>$val){
                $temp = [];
                $temp['No'] = (int)$key + 1;
                $temp['GoodsID'] = $val->goods_id;
                $temp['goodsNM'] = $val->goodName;
                $temp['logo'] = $val->goodIcon;
                if($temp['logo'] && !strpos("http",$temp['logo'])){
                    $temp['logo'] = env("QINIU_IMG_HOST").$temp['logo'];
                }
                $temp['happerDate'] = date('Y-m-d H:i',$val->created_at->timestamp);
                if($val->status != 2){
                    $rentTime = ($val->end_time - $val->start_time)/60;
                }else{
                    $rentTime = (time() - $val->start_time)/60;
                }
                if($rentTime <= 0){
                    $rentTime = 0;
                }
                $rentTime = floor( ($rentTime*0.95)* 10 ) /10;
                $temp['Unit'] = $rentTime;
                $temp['Amount'] = $val->amount;//支付总额
                $temp['PAmount'] = 0;//个人支付金额
                $temp['CAmount'] = 0;//企业支付金额 //
                if($val->status == 1){
                    $temp['status'] = "体验完毕";
                }else if($val->status == 0){
                    $temp['status'] = "失败";
                }else if($val->status == 2){
                    $temp['status'] = "使用中";
                }else{
                    $temp['status'] = "待处理";
                }
                $box = Cabinet::select('*')
                    ->where('id','=',$val->cabinet_id)
                    ->where('is_delete','=',0)
                    ->first();
                $temp['eno'] = "";
                $temp['bno'] = "";
                if($box){
                    $cell = CabinetCell::select('*')
                        ->where('cabinet_id','=',$val->cabinet_id)
                        ->where('id','=',$val->cell_id)
                        ->where('is_delete','=',0)
                        ->first();
                    $temp['eno'] = $box->code?$box->code:'';
                    $temp['bno'] = $cell->code?$cell->code:'';
                }
                $data['data'][] = $temp;
            }
        }
        $retA = array_merge($retArr,$data);
        return $retA;
    }
    //提现记录
    public function getUserAppOutMoneylist() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $goodsList = Orders::select('orders.*')
                ->join('user','user.id','=','orders.user_id')
                ->where('orders.type','=',5)
                ->where('user.phone','=',$mobile)
                ->where('user.status','=',1)
                ->where('user.is_delete','=',0)
                ->where('orders.is_delete','=',0)
                ->get();
        $retArr["msg"]= "获取成功";
        $retArr["result"] = 1;
        $retArr["mobile"] = $mobile;
        $data['data'] = [];
        if(count($goodsList)){
            foreach ($goodsList as $val){
                $temp = [];
                $temp['No'] = $val->id;
                $temp['AppAmount'] = $val->amount;//金额
                $temp['appDate'] = date('Y-m-d H:i',$val->created_at->timestamp);
                switch ($val->type){
//                    1 消费 2 交押金 3 退押金 4 充值
                    case 1:
                        $type = "消费";
                        break;
                    case 2:
                        $type = "交押金";
                        break;
                    case 3:
                        $type = "退押金";
                        break;
                    case 4:
                        $type = "充值";
                        break;
                    case 5:
                        $type = "提现";
                        break;
                    default :
                        $type = "";
                        break;
                }
                $temp['cls'] = $type;
                if($val->status == 1){
                    $temp['status'] = "成功";
                }else if($val->status == 0){
                    $temp['status'] = "失败";
                }else if($val->status == 2){
                    $temp['status'] = "待支付";
                }else{
                    $temp['status'] = "待处理";
                }
                $data['data'][] = $temp;
            }
        }
        return array_merge($retArr,$data);
    }
    //提现申请
    public function getUserAppOutMoney() {
        $mobile = Input::get('mobile');
        $money = Input::get('money');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$money){
            $retArr["msg"]= "请传入申请金额";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            if($user->balance < $money){
                $retArr["msg"]= "余额不足，请先充值~！";
                $retArr["result"] = 0;
                return $retArr;
            }
            $order = new Orders();
            $order->user_id = $user->id;
            $order->amount = $money;
            $order->type = 5;
            $order->status = 2;
            $ret = $order->save();
            if($ret){
                $retArr["msg"]= "提交成功~！";
                $retArr["result"] = 1;
                return $retArr;
            }
        }
        $retArr["msg"]= "申请失败，请联系管理员~！";
        $retArr["result"] = 0;
        return $retArr;
    }
    //租用商品
    public function UserRent() {
        $mobile = Input::get('mobile');
        $eno = Input::get('eno');
        $bno = Input::get('bno');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$eno){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$bno){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
//            if(!$user->client_id || $user->is_bind != 2){//普通用户
//                if($user->deposit <= 0){
//                    $retArr["msg"]= "您尚未充押金，无法取用~！";
//                    $retArr["result"] = 0;
//                    return $retArr;
//                }
//            }
            $ord = Orders::select('*')
                    ->where('user_id','=',$user->id)
                    ->where('type','=',1)
                    ->where('is_delete','=',0)//
                    ->where('status','=',2)
                    ->first();
            if($ord){
                $retArr["msg"]= "正在租用其他商品";
                $retArr["result"] = 0;
                return $retArr;
            }
            $box = Cabinet::select('*')
                ->where('code','=',$eno)
                ->where('is_delete','=',0)
                ->first();
            if(!$box){
                $retArr["msg"]= "未获取到箱体号";
                $retArr["result"] = 0;
                return $retArr;
            }
            if($box->client_id){//企业柜子
                if(!$user->client_id || $user->is_bind != 2){//普通用户
                    Log::info("普通用户自动绑定企业");
                    $user->client_id = $box->client_id;
                    $user->is_bind = 2;
                    $user->save();
                }
            }else{
                if(!$user->client_id || $user->is_bind != 2){//普通用户
                    if($user->deposit <= 0){
                        $retArr["msg"]= "您尚未充押金，无法取用~！";
                        $retArr["result"] = 0;
                        return $retArr;
                    }
                }
            }
            $cell = CabinetCell::select('*')
                    ->where('cabinet_id','=',$box->id)
                    ->where('code','=',$bno)
                    ->where('is_delete','=',0)
                    ->first();
            if($cell){
                if($cell->status == 1){
                    $retArr["msg"]= "设备已经被租用~！";
                    $retArr["result"] = 0;
                    return $retArr;
                }
                if($cell->status == 2){
                    $retArr["msg"]= "设备被保修，请选择其他设备~！";
                    $retArr["result"] = 0;
                    return $retArr;
                }
                $good = Goods::select('*')
                        ->where('status','=',1)
                        ->where('is_delete','=',0)
                        ->where('id','=',$cell->goods_id)
                        ->first();
                $ret = $this->isFree($cell->price_id);
                if($ret){//收费
                    if($user->balance <= 0){//普通用户
                        $retArr["msg"]= "余额不足，请先充值~！";
                        $retArr["result"] = 0;
                        return $retArr;
                    }
                }
                $cell->status = 1;
                $cell->save();
                
                $order = new Orders();
                $order->user_id = $user->id;
                if($user->is_bind == 2){
                    $order->client_id = $user->client_id;
                }
                $order->cabinet_id = $cell->cabinet_id;
                $order->cell_id = $cell->id;
                $order->goods_id = $cell->goods_id;
                $order->type = 1;
                $order->start_time = time();
                $order->status = 2;
                $ret = $order->save();
                if($ret){
                    $this->openBox($eno,$bno);
                    $retArr["msg"]= "提交成功~！";
                    $retArr["result"] = 1;
                    return $retArr; //
                }else{
                    $retArr["msg"]= "申请失败，请联系管理员~！";
                    $retArr["result"] = 1;
                    return $retArr; 
                }
            }
        }
    }
    
    /*******************************************************开箱**************************/
    public function openBox($eno,$bno){
        $url = 'http://cos.wondware.com/mq/device/service';
        $post_data['deviceId']       = $eno;
        $post_data['lockAddress']      = $bno;
        $post_data['commandType'] = 'openOne';
        $post_data['sourceType']    = 'G';
        $post_data['lockTotalNum']    = '1';
        $post_data['uqKey']    = '635B6252907764480F8A2380';
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $res = $this->request_post($url, $post_data);  
        return $res;
    }
    
    public function mReturnOpenBox() {
        $eno = Input::get('eno');
        $bno = Input::get('bno');
        $ret = $this->ReturnOpenBox($eno,$bno);
        return $ret;
    }
    function ReturnOpenBox($eno,$bno)
    {
            $url = 'http://cos.wondware.com/mq/device/service';
            $post_data['deviceId']       = $eno;
            $post_data['lockAddress']      = $bno;
            $post_data['commandType'] = 'openOne';
            $post_data['sourceType']    = 'S';
            $post_data['lockTotalNum']    = '1';
            $post_data['uqKey']    = '635B6252907764480F8A2380';
            $o = "";
            foreach ( $post_data as $k => $v ) 
            { 
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);

            $res = $this->request_post($url, $post_data);       
            //print_r($res);
            return $res;
    }
    public function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
    }
    //获取租用列表
    public function getUserRend() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();

        if($user){
            $orderList = Orders::select('*')
                    ->where('user_id','=',$user->id)
                    ->where('type','=',1)
                    ->where('is_delete','=',0)
                    ->get();
            $data['data'] = [];
            $retArr["msg"]= "获取成功";
            $retArr["result"] = 1;
            $retArr["mobile"] = $mobile;
            if(count($orderList)>0){
                foreach ($orderList as $val){
                    $temp = [];
                    $temp['No'] = $val->id;
                    $temp['GoodsID'] = $val->goods_id;
                    $goods = Goods::select('*')
                            ->where('id','=',$val->goods_id)
                            ->first();
                    $temp['goodsNM'] = isset($goods->name)?$goods->name:"";
                    $temp['happerDate'] = date('Y-m-d H:i',$val->created_at->timestamp);
                    $temp['logo'] = "log";
                    $temp['eno'] = $val->cabinet_id;
                    $temp['bno'] = $val->cell_id;
                    if($temp['logo'] && !strpos("http",$temp['logo'])){
                        $temp['logo'] = env("QINIU_IMG_HOST").$temp['logo'];
                    }
                    $data['data'][] = $temp;
                }
            }
            return array_merge($retArr,$data);
        }
    }
    //归还商品
    public function UserReturn() {
        $mobile = Input::get('mobile');
        $eno = Input::get('eno');
        $bno = Input::get('bno');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$eno){
            $retArr["msg"]= "未获取到箱体号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$bno){
            $retArr["msg"]= "未获取到柜号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            $box = Cabinet::select('*')
                ->where('code','=',$eno)
                ->where('is_delete','=',0)
                ->first();
            if(!$box){
                $retArr["msg"]= "未获取到箱体号";
                $retArr["result"] = 0;
                return $retArr;
            }
            $cell = CabinetCell::select('*')
                    ->where('cabinet_id','=',$box->id)
                    ->where('code','=',$bno)
                    ->where('is_delete','=',0)
                    ->first();
            if(!$cell){
                $retArr["msg"]= "未获取到柜号";
                $retArr["result"] = 0;
                return $retArr;
            }
            
            $order = Orders::select('*')
                    ->where('user_id','=',$user->id)
                    ->where('type','=',1)
                    ->where('cabinet_id','=',$box->id)
                    ->where('cell_id','=',$cell->id)
                    ->where('is_delete','=',0)
                    ->where('status','=',2)
                    ->first();
            $arr = with(new Goods())->countFee($user->client_id);
            if(!$arr){
                $retArr["msg"]= "柜子异常，请联系管理员~！";
                $retArr["result"] = 0;
                return $retArr;
            }
            if($user->client_id && $user->is_bind == 2){//企业用户
                //个人支付  + 企业支付
                $user->balance = $user->balance - $arr['pFee'];//可能为负数
                $user->save();
                $client = Client::select('*')
                        ->where('id','=',$user->client_id)
                        ->where('status','=',1)
                        ->where('is_delete','=',0)
                        ->first();
                $client->balance = $client->balance - $arr['cFee'];//可能为负
                $client->save();
                //$arr['minute'] 分钟怎么记录
            }else{
                $order->status = 1;
                $order->pay_type = 1;
                $order->end_time = time();
                $order->save();
//                  订单完成
                $user->balance = $user->balance - $arr['pFee'];//可能为负数
                $user->save();
            }
            $cell->status = 0;
            $cell->save();
        }else{
            $retArr["msg"]= "柜子异常，请联系管理员~！";
            $retArr["result"] = 0;
            return $retArr;
        }
    }
    
    //交押金
    public function UserAddYJMoney() {
        $mobile = Input::get('mobile');
        $money = Input::get('money');
        $wxorder = Input::get('wxorder');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$money){
            $retArr["msg"]= "没有充值额度";
            $retArr["result"] = 0;
            return $retArr;
        }
        if(!$wxorder){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            $user->deposit += $money;
            $ret = $user->save();
            
            $order = new Orders();
            $order->user_id = $user->id;
            $order->wxorder = $wxorder;
            if($user->is_bind == 2){
                $order->client_id = $user->client_id;
            }
            $order->amount = $money;
            $order->type = 2;
            $order->pay_type = 1;
            $order->status = 2;
            $ret = $order->save();
            if($ret){
                $retArr["msg"]= "缴纳成功~！";
                $retArr["result"] = 1;
                return $retArr;
            }
        }
        $retArr["msg"]= "报错，请联系管理员";
        $retArr["result"] = 0;
        return $retArr;
    }
    //是否缴纳押金
    public function isUserYJMoney() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            $order = Orders::select('*')
                    ->where('user_id','=',$user->id)
                    ->where('type','=',3)
                    ->where('status','=',2)
                    ->first();
            if($order){
                $retArr["msg"]= "已缴纳押金，但申请提现中~!~！";
                $retArr["result"] = 0;
                return $retArr;
            }
            Log::info("押金=".$user->deposit);
            if($user->deposit>0){
                Log::info("已缴纳押金");
                $retArr["msg"]= "已缴纳押金";
                $retArr["result"] = 1;
                return $retArr;
            }else{
                Log::info("未缴纳押金");
                $retArr["msg"]= "未缴纳押金";
                $retArr["result"] = 0;
                return $retArr;
            }
        }else{
            $retArr["msg"]= "请联系管理员";
            $retArr["result"] = 0;
            return $retArr;
        }
    }
    //申请提现
    public function RtUserYj() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            if($user->deposit <= 0){
                $retArr["msg"]= "押金未缴纳或者已经提现~！";
                $retArr["result"] = 0;
                return $retArr;
            }
            $order = new Orders();
            $order->user_id = $user->id;
            if($user->is_bind == 2){
                $order->client_id = $user->client_id;
            }
            $order->amount = 298;
            $order->type = 3;
            $order->status = 2;
            $ret = $order->save();
            if($ret){
                $retArr["msg"]= "提交成功~！";
                $retArr["result"] = 1;
                return $retArr;
            }
            $retArr["msg"]= "申请失败，请联系管理员~！";
            $retArr["result"] = 0;
            return $retArr;
        }
    }
    //获取用户可提现余额
    public function getTXMoney() {
        $mobile = Input::get('mobile');
        if(!$mobile){
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
        $user = $this->select('*')
                ->where('phone','=',$mobile)
                ->where('status','=',1)
                ->where('is_delete','=',0)
                ->first();
        if($user){
            $retArr["msg"]= "获取成功";
            $retArr["result"] = 1;
            $retArr["mobile"]= $mobile;
            $retArr["money"] = $user->balance;
            return $retArr;
        }else{
            $retArr["msg"]= "请传入手机号";
            $retArr["result"] = 0;
            return $retArr;
        }
    }
    public function isFree($priceId){
        $price = Price::select('*')
            ->where('is_delete','=',0)
            ->where('id','=',$priceId)
            ->first();
        if(!$price){
            return false;
        }
        if($price->price){
            $priceArr = json_decode($price->price,TRUE);
            if(!is_array($priceArr)){
                return false;
            }
            foreach ($priceArr as $val){
                if($val['price'] != 0){
                    return true;
                }
            }
        }
    }
}